//
//  StudentPerformanceTableViewController.swift
//  StudentPerformance
//
//  Created by ap0stader on 2023/11/2.
//

import UIKit

class StudentPerformanceTableViewController : UITableViewController {
    
    var studentsInfo : StudentsInfo!
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let row = tableView.indexPathForSelectedRow?.row {
            let theStudent = studentsInfo.studentsCollection[row] as! Student
            let thedetailController = segue.destination as! DetailController
            thedetailController.theStudent = theStudent
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return studentsInfo.studentsCollection.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) as! StudentCell
        
        let student = studentsInfo.studentsCollection[indexPath.row]
        
        cell.nameLabel.text = student.value(forKey: "name") as? String
        cell.numberLabel.text = student.value(forKey: "id") as? String
        cell.scoreLabel.text = "\(student.value(forKey: "score") as! Int16)"
        
        print(student.value(forKey: "score") as! Int16)
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let theStudent = studentsInfo.studentsCollection[indexPath.row] as! Student
            studentsInfo.deleteStudent(theStudent)
            tableView.deleteRows(at: [indexPath], with: .automatic)
        }
    }
    
    override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        studentsInfo.transferPosition(sourceIndex: sourceIndexPath.row, destinationIndex: destinationIndexPath.row)
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100;
    }
    
    @objc func refreshing() {
        if(refreshControl?.isRefreshing == true) {
            refreshControl?.attributedTitle = NSAttributedString("loading...")
            refreshControl?.endRefreshing()
            refreshControl?.attributedTitle = NSAttributedString("refresing")
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        // 新版本不写没有什么问题
        let statusBarHeight = view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 30
        
        let insets = UIEdgeInsets(top: statusBarHeight, left: 0, bottom: 0, right: 0)
        
        tableView.contentInset = insets
        tableView.scrollIndicatorInsets = insets
        
        let theRefreshControl = UIRefreshControl()
        
        theRefreshControl.attributedTitle = NSAttributedString("refreshing")
        theRefreshControl.addTarget(self, action: #selector(refreshing), for: .valueChanged)
        
        refreshControl = theRefreshControl
    }
    
    @IBAction func shiftEditMode(_ sender: UIButton) {
        if isEditing {
            sender.setTitle("Edit", for: .normal)
            setEditing(false, animated: true)
        } else {
            sender.setTitle("Done", for: .normal)
            setEditing(true, animated: true)
        }
        
    }
    
    @IBAction func addStudent(_ sender: UIButton) {
        let alert = UIAlertController(title: "添加一条学生记录",
                                      message: "请依次输入学生的姓名、学号、成绩",
                                      preferredStyle: .alert)
        
        alert.addTextField{(textField : UITextField) -> Void in textField.placeholder = "姓名"}
        alert.addTextField{(textField : UITextField) -> Void in textField.placeholder = "学号"}
        alert.addTextField{(textField : UITextField) -> Void in textField.placeholder = "成绩"}
        
        let saveAction = UIAlertAction(title: "Save", style: .default) {
            [unowned self] action in
            
            let theName = alert.textFields?[0].text
            let theId = alert.textFields?[1].text
            let theScore = alert.textFields?[2].text
            
            let theStudent = self.studentsInfo.addStudent(name: theName!, id: theId!, score: Int(theScore!)!)
            
            if let theIndex = self.studentsInfo.studentsCollection.firstIndex(of: theStudent) {
                let theIndexPath = IndexPath(row: theIndex, section: 0)
                self.tableView.insertRows(at: [theIndexPath], with: .automatic)
            }
        }
        
        let cancelAction = UIAlertAction(title: "Cancel",
                                         style: .default)
        
        alert.addAction(cancelAction)
        alert.addAction(saveAction)
        
        present(alert, animated: true)
    }
}
